<?php
class SitemapWidget extends FWidget
{
    private $_activePages;
    public function run()
    {
        $workflowId = 0;
        $siteId = 0;
        $result = FSM::run('Cms.Workflow.lookup');
        if (!$result->hasErrors())
        {
            $workflowId = $result->model->id;
            $siteId = $result->model->site_id;
        }
        
        //find active pages in workflow
        $command = Yii::app()->db->createCommand();
        $this->_activePages = $command->select('*')
            ->from(SITE_TABLE_PREFIX.'page_current_revision')
            ->where('workflow_id=:workflow_id', array(':workflow_id'=>$workflowId))
            ->queryColumn();
        
        $criteria=new CDbCriteria;
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_current_revision pcr ON pcr.page_id = t.id';
        $criteria->compare('pcr.workflow_id', $workflowId);
        $criteria->compare('site_id', $siteId);
        $criteria->compare('parent_id', 0);
        $criteria->compare('include_in_sitemap', true);
        $criteria->compare('status', true);
        $criteria->order = 'ordering';
        $models = Page::model()->findAll($criteria);
        return $this->render('sitemap', array('models'=>$models), true);
    }
    
    protected function renderNestedPage($models)
    {
        foreach ($models as $index => $model) {
            if (in_array($model->id, $this->_activePages) === false) continue;
            echo '<li id="item-'.$model->id.'">';
            echo CHtml::link($model->title, (is_object($model->defaultUrl) ? Yii::app()->request->hostInfo.Yii::app()->request->baseUrl.'/'.ltrim($model->defaultUrl->url, '/') : '#'));
            $children = $model->children(array('condition'=>'include_in_sitemap = :include_in_sitemap', 'params'=>array(':include_in_sitemap'=>true)));
            if (is_array($children) && count($children)) {
                echo '<ul>';
                $this->renderNestedPage($children);
                echo '</ul>';
            }
            echo '</li>';
        }
    }
}
